#include "Timestamp.h"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <stdio.h>
#include <time.h>

//编译时断言
static_assert(sizeof(Timestamp) == sizeof(int64_t), "sizkeof(Timestamp error)");

const std::string Timestamp::toString() const
{
    char buff[64] = {0};
    int64_t seconds = m_microSecondsSinceEpoch / kMicroSecondsPerSecond;
    int64_t microSeconds = m_microSecondsSinceEpoch % kMicroSecondsPerSecond;
    snprintf(buff,sizeof(buff)-1,"%lld.%06lld",(long long int )seconds,(long long int)microSeconds);
    return buff;
}

const std::string Timestamp::toFormattedString(bool showMicroSeconds) const
{
    time_t seconds = static_cast<time_t>(m_microSecondsSinceEpoch / kMicroSecondsPerSecond);
    struct tm tm_time;
    tm_time = *(localtime(&seconds));
    char buff[32];

    if(showMicroSeconds)
    {
        int microseconds = static_cast<int>(m_microSecondsSinceEpoch % kMicroSecondsPerSecond);

        snprintf(buff,sizeof(buff),"%4d%02d%02d %02d:%02d:%02d.%06d",
        tm_time.tm_year+1900,tm_time.tm_mon+1,tm_time.tm_mday,
        tm_time.tm_hour,tm_time.tm_min,tm_time.tm_sec,
        microseconds);
    }
    else
    {
        snprintf(buff,sizeof(buff),"%4d%02d%02d %02d:%02d:%02d",
        tm_time.tm_year+1900,tm_time.tm_mon+1,tm_time.tm_mday,
        tm_time.tm_hour,tm_time.tm_min,tm_time.tm_sec);    
    }
    
    return buff;

}

Timestamp Timestamp::now()
{   
    std::chrono::time_point<std::chrono::system_clock,std::chrono::microseconds> now = 
        std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::system_clock::now());
    
    int64_t mircorSeconds = now.time_since_epoch().count();
    Timestamp time(mircorSeconds);
    return time;
}

Timestamp Timestamp::invalid()
{   
    return Timestamp();
}
